package com.zsj.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsj.entity.HttpReturnMessage;
import com.zsj.entity.RechargeResponse;
import com.zsj.enums.ErrorCodeEnum;
import com.zsj.enums.NotifyStatusEnum;
import com.zsj.enums.OrderStatusEnum;
import com.zsj.mysql.entity.DyMobileRecharge;
import com.zsj.mysql.entity.DyNotify;
import com.zsj.mysql.service.IDyMobileRechargeService;
import com.zsj.mysql.service.IDyNotifyService;
import com.zsj.util.DateUtil;
import com.zsj.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author:
 * @Date:
 */
@Slf4j
@Service
public class NotifyDyService {

    @Autowired
    private SignService signService;

    @Autowired
    private IDyNotifyService dyNotifyService;

    @Autowired
    private IDyMobileRechargeService mobileRechargeService;

    public boolean notifyDy(DyMobileRecharge record) {
        // 默认为系统通知
        return notifyDy(record, 0);
    }

    public boolean notifyDy(DyMobileRecharge record, Integer notifyType) {
        try {
            log.info("开始通知请求方");
            JSONObject json = new JSONObject();
            json.put("Code", ErrorCodeEnum.SUCCESS.getCode());
            json.put("Msg", ErrorCodeEnum.SUCCESS.getMsg());
            RechargeResponse context = new RechargeResponse();
            context.setAppId(record.getAppId());
            context.setSupplierCode(record.getSupplierCode());
            context.setChargeNo(record.getChargeNo());
            context.setChannelOrderNo(record.getChannelChargeNo());
            context.setOrderStatus(OrderStatusEnum.findByCode(record.getOrderStatus() + "").name());
            context.setContractPrice(record.getContractPrice());
            context.setFinishTime(record.getFinishTime());
            context.setOriginCarrierCode(record.getOriginCarrierCode());
            context.setCurrentCarrierCode(record.getOriginCarrierCode());

            context.setAdCode(record.getAdCode());
            context.setProductDenomination(record.getProductDenomination());
            // 签名
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> responseMap = mapper.readValue(JSONObject.toJSONString(context), Map.class);
            String sign = signService.sign(responseMap);
            context.setSign(sign);
            json.put("Data", JSONObject.toJSONString(context));
            // 保存通知表
            DyNotify dyNotify = new DyNotify();
            dyNotify.setRechargeId(record.getId());
            dyNotify.setNotifyUrl(record.getNotifyUrl());
            dyNotify.setNotifyContent(json.toJSONString());
            dyNotify.setNotifyTime(DateUtil.getCurrentDateTime());
            dyNotify.setNotifyType(notifyType);
            dyNotifyService.save(dyNotify);
            boolean flag = send(json.toJSONString(), record.getNotifyUrl());
            Integer notifyStatus;
            if (flag) {
                notifyStatus = NotifyStatusEnum.SUCCESS.getCode();
            } else {
                notifyStatus = NotifyStatusEnum.FAILED.getCode();
            }
            // 更新订单表通知状态、次数、最新时间
            String month = String.valueOf(record.getTxnDate()).substring(0, 6);
            mobileRechargeService.updateNotify(month, notifyStatus, DateUtil.getCurrentDateTime(), record.getChargeNo());
            // 更新通知表状态
            dyNotify.setNotifyStatus(notifyStatus);
            dyNotifyService.updateById(dyNotify);
            return flag;
        } catch (Exception e) {
            log.error("通知请求方异常", e);
            return false;
        }
    }

    private boolean send(String context, String url) {
        log.info("回调请求方，请求参数:{}, url:{}", context, url);
        try {
            Map<String, String> headers = new HashMap<>(2);
            headers.put("Content-Type", "application/json");
            HttpReturnMessage httpReturnMessage = HttpUtil.doPost(url, context, headers, 1000, 5000);
            log.info("回调响应:{}", httpReturnMessage);
            if (httpReturnMessage.isSuccess()) {
                log.info("回调成功");
                return true;
            } else {
                log.info("回调失败");
                return false;
            }
        } catch (Exception e) {
            log.error("通知请求方失败", e);
            return false;
        }
    }
}
